<template>
	<view class="consultOrder">
		<u-navbar ref="navbarRef" class="van-nav-bar" :placeholder="true" title="咨询订单" @leftClick="leftClick" :autoBack="false"></u-navbar>
		<view class="process">
			<u-steps :current="current" inactiveColor="#b0b0b0">
				<u-steps-item title="选择服务"></u-steps-item>
				<u-steps-item title="选择来访者"></u-steps-item>
				<u-steps-item title="提交订单"></u-steps-item>
				<u-steps-item title="确认支付"></u-steps-item>
			</u-steps>
		</view>
		<scroll-view :style="{ height: domHeight }" class="scrollWrap" :enhanced="true" scroll-y :bounces="false" :show-scrollbar="false">
			<view class="container">
				<view class="wrap">
					<view class="title">服务名称</view>
					<view class="sel-wrap">
						<view
							v-if="recordId && current === '2'"
							:class="consultationTypeId === index ? 'selActive' : ''"
							v-for="(item, index) in consultationTypeList"
							:key="index"
						>
							{{ item.name }}
						</view>
						<view
							v-if="!recordId && current !== '2'"
							:class="consultationTypeId === index ? 'selActive' : ''"
							v-for="(item, index) in consultationTypeList"
							:key="index"
							@click="consultationTypeId = index"
						>
							{{ item.name }}
						</view>
					</view>
					<view class="title">咨询方式</view>
					<view class="sel-wrap">
						<view
							v-if="recordId && current === '2'"
							:class="consultationMethodId === item.id ? 'selActive' : ''"
							v-for="(item, index) in consultationMethodList"
							:key="index"
						>
							{{ item.name }}
						</view>
						<view
							v-if="!recordId && current !== '2'"
							:class="consultationMethodId === item.id ? 'selActive' : ''"
							@click="consultationMethodId = item.id"
							v-for="(item, index) in consultationMethodList"
							:key="index"
						>
							{{ item.name }}
						</view>
					</view>
					<view class="title">选择咨询语言</view>
					<view class="sel-wrap">
						<view class="selActive">中文</view>
					</view>
					<!-- <view class="seeAddress">面询地址：xxxxx</view> -->
					<view class="title">咨询日期</view>
					<view class="consultDate">
						<view
							v-if="recordId && current === '2'"
							:class="!item.state ? 'selDateActiveGray' : consultDateIndex === index ? 'selActive' : ''"
							v-for="(item, index) in consultDateList"
							:key="index"
						>
							<view>{{ item.week }}</view>
							<view>{{ item.Md }}</view>
						</view>
						<view
							v-if="!recordId && current !== '2'"
							:class="!item.state ? 'selDateActiveGray' : consultDateIndex === index ? 'selActive' : ''"
							@click="handleSelConsultData(item, index)"
							v-for="(item, index) in consultDateList"
							:key="index"
						>
							<view>{{ item.week }}</view>
							<view>{{ item.Md }}</view>
						</view>
					</view>
					<view class="title">咨询时间</view>
					<view v-if="recordId && current === '2'" class="sel-wrap sel-wrap-time">
						<view
							:class="item.consultationStatus !== '1' ? (timeIndex === index ? 'selActive' : '') : 'selDateActiveGray'"
							v-for="(item, index) in timeList"
							:key="index"
						>
							{{ item.startScheduleTime }}-{{ item.endScheduleTime }}
						</view>
					</view>
					<view v-if="consultDateList[consultDateIndex].state && !recordId && current !== '2'" class="sel-wrap sel-wrap-time">
						<view
							:class="item.consultationStatus !== '1' ? (timeIndex === index ? 'selActive' : '') : 'selDateActiveGray'"
							@click="handleTime(item, index)"
							v-for="(item, index) in timeList"
							:key="index"
						>
							{{ item.startScheduleTime }}-{{ item.endScheduleTime }}
						</view>
					</view>
					<view v-if="!consultDateList[consultDateIndex].state" style="font-size: 26rpx; color: #424242">已约满</view>
					<view v-if="allTimeDate" class="title">您的预约咨询时间是:</view>
					<view v-if="allTimeDate" class="consultTime">
						<view>{{ allTimeDate }}</view>
					</view>
				</view>
			</view>
			<!-- <view style="height: 166rpx; width: 100%"></view> -->
		</scroll-view>
		<view class="bot-btn">
			<view>
				<text>咨询费：</text>
				<text>¥</text>
				<text>{{ consultationTypeList[consultationTypeId].cost }}</text>
			</view>
			<view v-if="!allTimeDate">下一步</view>
			<view class="activeBtn" v-if="allTimeDate && !recordId" @click="consultNext">下一步</view>
			<view class="activeBtn" v-if="recordId && current === '2'" @click="submitOrder">提交订单</view>
		</view>
	</view>
</template>
<script>
import { consultationRecordList, getExpertScheduleList, getExpert, addAppointment } from '@/api/consult/index.js';
export default {
	data() {
		return {
			domHeight: '',
			//咨询类型
			consultationTypeList: [
				{
					id: 1,
					name: '个人用户个体咨询',
					cost: ''
				},
				{
					id: 2,
					name: '个人用户家庭咨询',
					cost: ''
				}
			],
			consultationTypeId: 0,
			//咨询方式
			consultationMethodList: [
				{
					id: 1,
					name: '电话咨询'
				},
				{
					id: 2,
					name: '线上语音'
				},
				{
					id: 3,
					name: '线上视频'
				},
				{
					id: 4,
					name: '当面咨询'
				}
			],
			consultationMethodId: 1,
			consultDateList: [],
			consultDateIndex: -1,
			timeList: [],
			timeIndex: -1,
			current: '0',
			experId: '',
			allTimeDate: '',
			// fromPage: '',
			recordId: ''
		};
	},
	onLoad(options) {
		this.experId = options.id;
		//查询专家信息
		getExpert(this.experId).then((res) => {
			// console.log(res);
			this.consultationTypeList[0].cost = res.data.individualConsultCost ?? '';
			this.consultationTypeList[1].cost = res.data.familyConsultCost ?? '';
		});

		// 获取当前时间
		const now = new Date();
		// 计算明天的时间范围
		const tomorrowStart = new Date(now);
		tomorrowStart.setDate(tomorrowStart.getDate() + 1);
		tomorrowStart.setHours(0, 0, 0, 0); // 当天0点（计算用，不显示）

		const tomorrowEnd = new Date(tomorrowStart);
		tomorrowEnd.setDate(tomorrowEnd.getDate() + 1);
		tomorrowEnd.setMilliseconds(-1); // 当天结束（计算用，不显示）
		// 计算七天后的时间范围（从明天开始算第7天结束）
		const sevenDaysLaterEnd = new Date(tomorrowStart);
		sevenDaysLaterEnd.setDate(sevenDaysLaterEnd.getDate() + 6); // 7天后日期

		getExpertScheduleList({
			expertId: this.experId,
			scheduleBeginDate: this.formatDate(tomorrowStart),
			scheduleEndDate: this.formatDate(sevenDaysLaterEnd)
		}).then((res) => {
			this.consultDateList = this.processSchedule(res.rows);
			// this.timeList = this.consultDateList[this.consultDateIndex]?.time;
			let consultDataCopy = uni.getStorageSync('consultData')
			let consultData = consultDataCopy?JSON.parse(uni.getStorageSync('consultData')):{};
			if (consultData.experId) {
				this.recordId = uni.getStorageSync('recordId');
				this.current = '2';
				this.consultationTypeId = consultData.consultationTypeId;
				this.consultationMethodId = consultData.consultationMethodId;
				this.consultDateIndex = consultData.consultDateIndex;
				this.allTimeDate = consultData.allTimeDate;
				this.timeIndex =consultData.timeIndex;
				this.timeList = this.consultDateList[this.consultDateIndex]?.time;
			} else {
				const index = this.consultDateList.findIndex((element) => element.state);
				this.consultDateIndex = index;
			}
		});
	},
	onShow() {
		// if (uni.getStorageSync('recordId')) {
		// 	this.recordId = uni.getStorageSync('recordId');
		// 	this.current = '2';
		// }
		// const pages = getCurrentPages();
		// console.log(pages);
		// if (pages.length > 1) {
		// 	const prevPage = pages[pages.length - 2];
		// 	this.fromPage = prevPage.route;
		// 	console.log(this.fromPage);
		// 	// 	if (this.fromPage === 'subset/pages/consult/visitorProfile/archiveList' && uni.getStorageSync('recordId')) {
		// 	// 		this.current = '2';
		// 	// 		this.recordId = uni.getStorageSync('recordId');
		// 	// 		let obj = uni.getStorageSync('consultData');
		// 	// 		this.consultationTypeId = obj.consultationTypeId;
		// 	// 		this.consultationMethodId = obj.consultationMethodId;
		// 	// 		this.consultDateIndex = obj.consultDateIndex;
		// 	// 		this.allTimeDate = obj.allTimeDate;
		// 	// 		this.timeIndex = uni.getStorageSync('timeIndex')*1;
		// 	// 		this.timeList = this.consultDateList[this.consultDateIndex]?.time;
		// 	// 	}else if(this.fromPage === 'subset/pages/consult/consultOrder/paymentPage'){
		// 	// 		this.current = 0;
		// 	// 		uni.removeStorageSync('recordId')
		// 	// 		this.consultationTypeId = 0;
		// 	// 		this.consultationMethodId = 1;
		// 	// 		// this.consultDateIndex = obj.consultDateIndex;
		// 	// 		// this.timeIndex = obj.timeIndex;
		// 	// 		// this.allTimeDate = obj.allTimeDate;
		// 	// 		// this.timeList = this.consultDateList[this.consultDateIndex]?.time;
		// 	// 	}else{
		// 	// 	}
		// }
	},
	watch: {
		consultDateIndex() {
			setTimeout(() => {
				this.timeList = this.consultDateList[this.consultDateIndex].time;
			}, 500);
		}
	},
	methods: {
		back() {
			if (this.fromPage === 'subset/subset/pages/consult/consultDetail') {
				uni.navigateBack();
			} else if (this.fromPage === 'subset/pages/consult/visitorProfile/visitorProfile') {
				uni.navigateBack({
					delta: 2
				});
			}
		},
		submitOrder() {
			addAppointment({
				amount: this.consultationTypeList[this.consultationTypeId].cost,
				appointmentDate: this.consultDateList[this.consultDateIndex].data,
				consultationMethod: this.consultationMethodId,
				consultationType: this.consultationTypeList[this.consultationTypeId].id,
				endTime: `${this.timeList[this.timeIndex].endScheduleTime}`,
				expertId: this.experId,
				recordId: this.recordId,
				scheduleId: this.timeList[this.timeIndex].id,
				startTime: `${this.timeList[this.timeIndex].startScheduleTime}`
			}).then((res) => {
				this.$tab.navigateTo(`/subset/pages/consult/consultOrder/paymentPage?id=${res.data.id}`);

				// console.log(res);
			});
		},
		handleSelConsultData(item, index) {
			if (item.state) {
				this.consultDateIndex = index;
				this.timeIndex = -1;
				this.allTimeDate = '';
			}
		},
		handleTime(item, index) {
			if (item.consultationStatus !== '1') {
				this.timeIndex = index;
				// uni.setStorageSync('timeIndex', this.timeIndex);
				this.allTimeDate = `${this.consultDateList[this.consultDateIndex].week} ${this.consultDateList[this.consultDateIndex].data} ${
					this.timeList[index].startScheduleTime
				}-${this.timeList[index].endScheduleTime}`;
			}
		},
		consultNext() {
			uni.setStorageSync(
				'consultData',
				JSON.stringify({
					consultationTypeId: this.consultationTypeId,
					consultationMethodId: this.consultationMethodId,
					timeIndex: this.timeIndex,
					consultDateIndex: this.consultDateIndex,
					allTimeDate: this.allTimeDate,
					experId: this.experId
				})
			);
			//查询档案
			consultationRecordList().then((res) => {
				// console.log(res);
				const list = res.rows;
				if (list.length !== 0) {
					this.$tab.navigateTo(`/subset/pages/consult/visitorProfile/archiveList`);
				} else {
					this.$tab.navigateTo(`/subset/pages/consult/visitorProfile/visitorProfile`);
				}
			});
		},
		formatDate(date) {
			// 提取并格式化日期组件
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		processSchedule(data) {
			data.sort((a, b) => new Date(a.scheduleDate) - new Date(b.scheduleDate));
			// 1. 按日期分组
			const grouped = data.reduce((acc, item) => {
				const date = item.scheduleDate;
				if (!acc[date]) {
					acc[date] = {
						data: date,
						week: this.getWeekDay(date),
						time: [],
						state: false,
						Md: this.formatToMMDD(date)
					};
				}
				acc[date].time.push({
					startScheduleTime: item.startScheduleTime,
					endScheduleTime: item.endScheduleTime,
					consultationStatus: item.consultationStatus,
					id: item.id
				});

				return acc;
			}, {});
			const targetStatuses = new Set(['0', '2']);
			// 2. 转换为数组并按时间排序
			return Object.values(grouped).map((group) => ({
				...group,
				state: group.time.some((t) => targetStatuses.has(t.consultationStatus)),
				time: group.time.sort((a, b) => {
					// 将时间转换为分钟数进行比较
					const toMinutes = (time) => {
						const [h, m] = time.split(':').map(Number);
						return h * 60 + m;
					};
					return toMinutes(a.startScheduleTime) - toMinutes(b.endScheduleTime);
				})
			}));
		},
		getWeekDay(dateString) {
			// 创建Date对象（自动解析常见日期格式）
			const date = new Date(dateString);
			// 验证日期有效性
			if (isNaN(date.getTime())) {
				return '无效日期格式';
			}
			// 星期映射表（0=周日，1=周一...6=周六）
			const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			return weekDays[date.getDay()];
		},
		formatToMMDD(dateStr) {
			// 分割日期字符串
			const [year, month, day] = dateStr.split('-');
			// 格式化为两位数并拼接
			return `${month.padStart(2, '0')}.${day.padStart(2, '0')}`;
		},
		leftClick() {
			uni.switchTab({
				url: '/pages/consult/index'
			});
		}
	},
	mounted() {
		const systemInfo = uni.getSystemInfoSync();
		let statusBarHeight = systemInfo.statusBarHeight || 20;
		// 示例计算公式（具体需根据组件实现调整）
		const height = statusBarHeight + 44 + 'px'; // 状态栏高度 + 导航栏内容高度
		this.domHeight = `calc(100% - ${height} - 150rpx - 166rpx)`;
	}
};
</script>

<style scoped lang="scss">
.consultOrder {
	width: 100%;
	height: 100%;
	overflow: hidden;
	background-color: rgb(232, 234, 239);
	.process {
		width: 100%;
		height: 150rpx;
		display: flex;
		align-items: center;
		background-color: #fff;

		::v-deep .u-steps-item__wrapper {
			width: 20px;
			height: 20px;
			border-radius: 50%;
			background-color: #fafafa;
		}

		::v-deep .u-steps-item__wrapper__circle__text {
			color: #fff !important;
		}
	}

	.selActive {
		background-color: rgba(92, 131, 253, 0.1) !important;
		color: #5c83fd !important;
		border: 2rpx solid #5c83fd !important;
	}

	.selDateActiveGray {
		background-color: rgba(247, 247, 247, 1) !important;
		color: rgba(220, 220, 220, 1) !important;
		border: 2rpx solid rgba(247, 247, 247, 1) !important;
	}

	.scrollWrap {
		width: 100%;
		height: 100%;
		background-color: rgb(232, 234, 239);
		padding: 10rpx 18rpx;
		box-sizing: border-box;
		border-radius: 0 0 10rpx 10rpx;
		.container {
			width: 100%;
			min-height: 100%;
			background-color: #fff;
			border-radius: 10rpx;
			.wrap {
				width: 100%;
				border-radius: 10rpx;
				padding: 10rpx 40rpx 40rpx 40rpx;
				box-sizing: border-box;
				.title {
					width: 100%;
					text-align: left;
					font-size: 30rpx;
					color: #000;
					font-weight: bold;
					margin-bottom: 26rpx;
					margin-top: 20rpx;
				}

				.sel-wrap {
					width: 100%;
					display: flex;
					justify-content: space-between;
					flex-wrap: wrap;
					// gap: 40rpx;
					> view {
						margin-bottom: 30rpx;
						padding: 20rpx 40rpx;
						border-radius: 10rpx;
						background-color: #fff;
						color: #000;
						border: 2rpx solid #a1a1a1;
					}
				}
				.sel-wrap-time {
					justify-content: flex-start !important;
					> view {
						margin-right: 50rpx;
					}
				}

				.seeAddress {
					width: calc(100% - 40rpx);
					padding: 10rpx 26rpx;
					background-color: #e7e7e7;
					color: #000;
					font-size: 26rpx;
					text-align: left;
					border-radius: 10rpx;
					margin: 20rpx auto 36rpx;
				}

				.consultDate {
					width: 100%;
					display: flex;
					height: 140rpx;
					margin: 30rpx 0 40rpx 0;
					overflow-x: auto;
					border-bottom: 2rpx solid #e7e7e7;
					padding-bottom: 40rpx;

					> view {
						width: 100rpx;
						height: auto;
						border-radius: 10rpx;
						background-color: #fff;
						color: #000;
						border: 2rpx solid #a1a1a1;
						margin-right: 20rpx;
						padding: 10rpx 16rpx;
						box-sizing: border-box;

						> view {
							width: 100%;
							text-align: center;
						}

						> view:nth-child(1) {
							margin-bottom: 4rpx;
						}
					}
				}

				.consultTime {
					width: 100%;

					> view {
						width: 100%;
						padding: 20rpx 0;
						border-radius: 10rpx;
						background-color: rgba(92, 131, 253, 0.1);
						color: #ffaa00;
						text-align: center;
						border: 2rpx solid #5c83fd;
						font-size: 30rpx;
					}
				}
			}
		}
	}

	.bot-btn {
		width: 100%;
		height: 166rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #fff;
		padding: 30rpx 30rpx 30rpx 0;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;

		> view:nth-child(1) {
			width: 50%;
			height: 106rpx;
			text-align: center;
			line-height: 106rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			> text:nth-child(1) {
				color: #444444;
				font-size: 26rpx;
			}

			> text:nth-child(2) {
				color: #ffaa00;
				font-size: 26rpx;
			}

			> text:nth-child(3) {
				color: #ffaa00;
				font-size: 50rpx;
				margin-left: 10rpx;
			}
		}

		> view:nth-child(2) {
			width: 50%;
			height: 106rpx;
			text-align: center;
			line-height: 106rpx;
			background: #e7e7e7;
			color: #bcbcbc;
			font-size: 32rpx;
			border-radius: 50rpx;
		}

		.activeBtn {
			background: #5c83fd !important;
			color: #fff !important;
		}
	}
}
</style>
